import style from './style.module.less'
import React, { ChangeEvent, useEffect, useState } from 'react'
import Head from '../../compontent/Header'
import { SearchOutlined } from '@ant-design/icons'
import {
  Button,
  ConfigProvider,
  Form,
  Input,
  Layout,
  message,
  Pagination,
  Switch,
} from 'antd'
import Sider from 'antd/es/layout/Sider'
import { Content } from 'antd/es/layout/layout'
import zhCN from 'antd/es/locale/zh_CN'
import ArticleItem from '../../compontent/ArticleItem'
import Article from '../../type'
import * as api from '../../services/api'

export default function Main(props: any) {
  let token: string = props.match.params.id
  let limit: number = 10
  let pageSizeOptions: string[] = ['5', '10', '20', '50', '100']

  const [keywords, setKeywords] = useState<string>('')
  const [dataSource, setDataSource] = useState<Article[]>([])
  const [pageIndex, setPageIndex] = useState<number>(1)
  const [pageSize, setPageSize] = useState<number>(5)
  const [total, setTotal] = useState<number>(0)
  const [timeIf, setTimeIf] = useState<boolean>(false)
  const [previewIf, setPreviewIf] = useState<boolean>(false)

  useEffect(() => {
    getDataSource(pageIndex, pageSize, keywords, timeIf, previewIf)
    getTotal()
  }, [])

  async function getDataSource(
    pageI: number,
    pageS: number,
    keyword: string,
    time: boolean,
    preview: boolean,
  ) {
    try {
      let getIf: boolean = true
      let res = await api.searchAllArticle(pageI, pageS, keyword)
      if (res.data.stat === 'ok') {
        let resData: Article[] = []
        if (resData.length > 0) resData = []
        if (res.data.data.items.length === 0) {
          getIf = false
        }
        res.data.data.items.map((data: any) => {
          let Article: Article = {
            author: data.author.account,
            banner: data.banner,
            content: data.content,
            ctime: data.ctime,
            preview: data.preview,
            subTitle: data.subTitle,
            tags: data.tags,
            title: data.title,
            id: data._id,
          }
          resData.push(Article)
          return null
        })
        if (preview) {
          resData.sort((a, b) => {
            if (a.preview < b.preview) return 1
            if (a.preview > b.preview) return -1
            return 0
          })
        }
        if (time) {
          resData.sort((a, b) => {
            if (a.ctime < b.ctime) return 1
            if (a.ctime > b.ctime) return -1
            return 0
          })
        }
        if (resData.length === 0) {
          message.destroy()
          message.success('当前关键字无相关数据')
          if (getIf) {
            // getDataSource(1, pageSize, '', timeIf, previewIf)
          }
        }
        setDataSource(resData)
      } else {
        message.destroy()
        message.error(res.data.msg)
      }
    } catch (e) {
      throw e
    }
  }

  async function getTotal() {
    try {
      let res = await api.searchAllArticle(0, 0, keywords)
      if (res.data.stat === 'ok') {
        setTotal(res.data.data.items.length)
      } else {
        message.destroy()
        message.error(res.data.msg)
      }
    } catch (e) {
      throw e
    }
  }

  function showTotal(num: number) {
    return <span>共 {num} 篇文章</span>
  }

  function pageOnchange(page: number, pageSize: any) {
    setPageIndex(page)
    setPageSize(pageSize)
    getDataSource(page, pageSize, keywords, timeIf, previewIf)
  }

  function getDataSourceByKeywords() {
    getDataSource(pageIndex, pageSize, keywords, timeIf, previewIf)
    getTotal()
    // setKeywords('')
  }

  function DataSortByTime() {
    setTimeIf(!timeIf)
    getDataSource(pageIndex, pageSize, keywords, !timeIf, previewIf)
  }

  function DataSortByPre() {
    setPreviewIf(!previewIf)
    getDataSource(pageIndex, pageSize, keywords, timeIf, !previewIf)
  }

  function setKeywordsOnchange(e: ChangeEvent<HTMLInputElement>) {
    if (e.target.value.length <= limit) {
      setKeywords(e.target.value)
    } else {
      setKeywords(e.target.value.slice(0, limit))
      message.destroy()
      message.error(`关键字长度不能超过${limit}个`)
    }
    if (e.target.value === '') {
      getDataSource(pageIndex, pageSize, keywords, timeIf, previewIf)
      getTotal()
    }
  }

  return (
    <div style={{ height: '100%' }}>
      <Head token={token} />
      <main className={style.main}>
        <Layout>
          <Sider className={style.sider}>
            <Form.Item className={style.form}>
              <Switch
                className={style.headerTime}
                defaultChecked={timeIf}
                checkedChildren={'按时间排序'}
                unCheckedChildren={'按默认排序'}
                onChange={DataSortByTime}
              />
              <Switch
                className={style.headerView}
                defaultChecked={previewIf}
                checkedChildren={'按浏览量排序'}
                unCheckedChildren={'按照默认排序'}
                onChange={DataSortByPre}
              />
              {/*<Button className={style.headerTime} onClick={DataSortByTime}>按时间排序</Button>*/}
              {/*<Button className={style.headerView} onClick={DataSortByPre}>按浏览量排序</Button>*/}
              <Input
                className={style.headerInput}
                value={keywords}
                onChange={setKeywordsOnchange}
                prefix={<SearchOutlined className={style.headerIcon} />}
              />
              <Button
                type={'primary'}
                className={style.search}
                onClick={getDataSourceByKeywords}>
                搜索
              </Button>
            </Form.Item>
          </Sider>
          <Content className={style.content}>
            <ConfigProvider locale={zhCN}>
              <Pagination
                className={style.Pagination}
                pageSizeOptions={pageSizeOptions}
                showSizeChanger={true}
                showQuickJumper={true}
                showTotal={(total) => showTotal(total)}
                total={total}
                pageSize={pageSize}
                current={pageIndex}
                onChange={(page, pageSize) => pageOnchange(page, pageSize)}
              />
            </ConfigProvider>
            {dataSource.map((data) => (
              <ArticleItem
                button={false}
                key={data.id}
                changeUpdate={undefined}
                update={null}
                token={token}
                dataSource={data}
              />
            ))}
          </Content>
        </Layout>
      </main>
    </div>
  )
}
